package com.soa.zuul.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.soa.zuul.entity.GatewayHttpApi;
import com.soa.zuul.util.Json;





@Service
@Transactional
public class GatewayHttpApiService {
	public final static Logger logger = LoggerFactory.getLogger(GatewayHttpApiService.class);
	@PersistenceContext
	private EntityManager entityManager;
	@Resource
	StringRedisTemplate stringRedisTemplate;
	private Session session;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Session getSession() {
		return this.getEntityManager().unwrap(org.hibernate.Session.class);
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@SuppressWarnings("unchecked")
	public List<GatewayHttpApi>  getGatewayHttpApiList() {
		Criteria userCriteria = this.getSession().createCriteria(GatewayHttpApi.class);
		userCriteria.add(Restrictions.eq("enabled", true));
		return userCriteria.list();
	}
	
	
	/**
	 * 根据path获取应用对象
	 * @param path
	 * @return
	 */
	public GatewayHttpApi getGatewayHttpApiByPath(String path) {
		GatewayHttpApi result = null;
		PathMatcher matcher = new AntPathMatcher();
		String rediskeypattern = GatewayHttpApi.class.getSimpleName() + ":path:*";
		List<String> gatewayHttpApiJsonList = null;
		try {
			List<String> keys = new ArrayList<String>(stringRedisTemplate.keys(rediskeypattern));
			gatewayHttpApiJsonList = stringRedisTemplate.opsForValue().multiGet(keys);
		} catch (Exception e) {
			logger.info("redsi读取GatewayHttpApi异常:"+e.getMessage());
			gatewayHttpApiJsonList = null;
			e.printStackTrace();
		}
		//redis中查出了数据从redis里面取
		if(gatewayHttpApiJsonList!=null && gatewayHttpApiJsonList.size()>0 ){
			for (String gatewayHttpApiJson : gatewayHttpApiJsonList) {
				GatewayHttpApi gatewayHttpApi = Json.GSON.fromJson(gatewayHttpApiJson,GatewayHttpApi.class);
				if (matcher.match(gatewayHttpApi.getPath(), path)) {
					result = gatewayHttpApi;
					break;
				}
			}
		}
		//redis查不出从数据库中取
		if(result==null){ 
			//如果redis里面没有数据，则从数据库同步到redis
				List<GatewayHttpApi> gatewayHttpApiDb = this.getGatewayHttpApiList();
				for (GatewayHttpApi gatewayHttpApi2 : gatewayHttpApiDb) {
					if (matcher.match(gatewayHttpApi2.getPath(), path)) {
						result = gatewayHttpApi2;
						try {
							String gatewayHttpApiValue = Json.GSON.toJson(gatewayHttpApi2);
							stringRedisTemplate.opsForValue().set(
									GatewayHttpApi.class.getSimpleName() + ":path:" + gatewayHttpApi2.getPath(),
									gatewayHttpApiValue);
							logger.info("成功同步到redsi:   GatewayHttpApi");
						} catch (Exception es) {
							es.printStackTrace();
						}
						break;
					}
				}
		}
		return result;
	}

}
